package com.neusoft.hifly.push.mobile.server.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.neusoft.hifly.commons.lang.LongUtil;
import com.neusoft.hifly.core.log.Log;
import com.neusoft.hifly.push.mobile.domain.JPushModelObj;
import com.neusoft.hifly.push.mobile.domain.ResultObj;
import com.neusoft.hifly.push.mobile.server.IJPushService;
import com.neusoft.hifly.push.mobile.util.JGPushUtil;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;

/**
 * Title: 消息推送中间件
 * <p>
 * Description: 推送实现
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service("jPushService")
public class JPushServiceImpl implements IJPushService {

	/**
	 * 向某些平台的所有设备推送alert消息
	 *
	 * @param masterSecret
	 *            极光推送MasterSecret
	 * @param appKey
	 *            极光推送AppKey
	 * @param platforms
	 *            某些平台(android,iOS),多个平台用,分隔
	 * @param message
	 *            推送消息内容
	 * @param sendUserLogicId
	 *            发送者logicId
	 * @param pushExtras
	 *            消息扩展参数
	 * @param pushType
	 *            推送环境类型(生产环境还是正式环境)
	 * @return 返回值
	 */
	@Override
	public ResultObj sendMobilePushAllPlatformAllDeviceAlert(final String masterSecret, final String appKey,
			final String platforms, final String message, final long sendUserLogicId,
			final Map<String, String> pushExtras, final String pushType) {

		final ResultObj resultObj = new ResultObj();

		try {
			final JGPushUtil jgPushUtil = new JGPushUtil(masterSecret, appKey);
			if (StringUtils.isEmpty(message)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("推送消息为空");

				return resultObj;
			}
			if (StringUtils.isEmpty(pushType)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("推送环境类型为空");

				return resultObj;
			}
			try {
				// 进行推送，返回推送结果
				final PushResult pushResult = jgPushUtil.buildPushObject_some_all_alert(platforms, message, pushType,
						pushExtras);
				Log.error("用户{}给所有平台所有设备发送一条推送消息", new Object[] { sendUserLogicId });

				resultObj.setResultFlag(true);
				resultObj.setObject(pushResult);
			} catch (final APIConnectionException e) {
				Log.error("用户{}给所有平台所有设备发送一条推送消息失败，原因为{}", new Object[] { sendUserLogicId, e.getMessage() });
				resultObj.setResultFlag(false);
				resultObj.setResultMsg(e.getMessage());
			} catch (final APIRequestException e) {
				Log.error("用户{}给所有平台所有设备发送一条推送消息失败，原因为{}", new Object[] { sendUserLogicId, e.getErrorMessage() });
				resultObj.setResultFlag(false);
				resultObj.setResultMsg(e.getErrorMessage());
			}
			return resultObj;
		} catch (final Exception e) {
			resultObj.setResultFlag(false);
			resultObj.setResultMsg(e.getMessage());
			return resultObj;
		}
	}

	/**
	 * 向某些平台，推送目标是别名为 alias，通知内容为 ALERT
	 *
	 * @param masterSecret
	 *            极光推送MasterSecret
	 * @param appKey
	 *            极光推送AppKey
	 * @param platforms
	 *            某些平台(android,iOS),多个平台用,分隔
	 * @param message
	 *            推送的消息
	 * @param sendUserLogicId
	 *            发送者用户逻辑ID
	 * @param alias
	 *            别名
	 * @param pushExtras
	 *            推送需要的其他扩展参数
	 * @param pushType
	 *            推送环境类型(生产环境还是正式环境)
	 * @return 返回值
	 */
	@Override
	public ResultObj sendMobilePushAllPlatformAliasAlert(final String masterSecret, final String appKey,
			final String platforms, final String message, final long sendUserLogicId, final String alias,
			final Map<String, String> pushExtras, final String pushType) {
		final ResultObj resultObj = new ResultObj();

		try {
			final JGPushUtil jgPushUtil = new JGPushUtil(masterSecret, appKey);
			if (StringUtils.isEmpty(message)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("推送消息为空");

				return resultObj;
			}
			if (LongUtil.isEmpty(sendUserLogicId)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("发送者逻辑ID为空");

				return resultObj;
			}
			if (StringUtils.isEmpty(alias)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("别名为空");

				return resultObj;
			}
			if (StringUtils.isEmpty(pushType)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("推送环境类型为空");

				return resultObj;
			}
			// 别名集合
			final List<String> aliasList = new ArrayList<String>();
			final String[] aliasArray = alias.split(",");
			if (aliasArray != null && aliasArray.length > 0) {
				for (final String element : aliasArray) {
					aliasList.add(element);
				}
			}
			try {
				// 进行推送，返回推送结果
				final PushResult pushResult = jgPushUtil.buildPushObject_some_alias_alert(platforms, aliasList, message,
						pushType, pushExtras);
				Log.error("用户{}给{}发送一条推送消息", new Object[] { sendUserLogicId, alias });

				// 返回的结果为JSON型
				//			JSONObject jsonObject = JSONObject.fromObject(pushResult.toString());
				//			if (jsonObject.containsKey("msg_id") && jsonObject.containsKey("sendno")) {
				//				// 消息ID（极光）
				//				String msgId = (String)jsonObject.get("msg_id");
				//				// 发送编号（极光）
				//				String sendNo = (String)jsonObject.get("sendno");
				//			}

				resultObj.setResultFlag(true);
				resultObj.setObject(pushResult);
			} catch (final APIConnectionException e) {
				Log.error("用户{}给{}发送一条推送消息失败，原因为{}", new Object[] { sendUserLogicId, alias, e.getMessage() });
				resultObj.setResultFlag(false);
				resultObj.setResultMsg(e.getMessage());
			} catch (final APIRequestException e) {
				Log.error("用户{}给{}发送一条推送消息失败，原因为{}", new Object[] { sendUserLogicId, alias, e.getErrorMessage() });
				resultObj.setResultFlag(false);
				resultObj.setResultMsg(e.getErrorMessage());
			}
			return resultObj;
		} catch (final Exception e) {
			resultObj.setResultFlag(false);
			resultObj.setResultMsg(e.getMessage());
			return resultObj;
		}
	}

	/**
	 * 向某些平台，推送目标是标签名为 tags，通知内容为 ALERT
	 *
	 * @param masterSecret
	 *            极光推送MasterSecret
	 * @param appKey
	 *            极光推送AppKey
	 * @param platforms
	 *            某些平台(android,iOS),多个平台用,分隔
	 * @param message
	 *            推送的消息
	 * @param sendUserLogicId
	 *            发送者用户逻辑ID
	 * @param tags
	 *            标签名
	 * @param pushExtras
	 *            推送需要的其他扩展参数
	 * @param pushType
	 *            推送环境类型(生产环境还是正式环境)
	 * @return 返回值
	 */
	@Override
	public ResultObj sendMobilePushAllPlatformTagsAlert(final String masterSecret, final String appKey,
			final String platforms, final String message, final long sendUserLogicId, final String tags,
			final Map<String, String> pushExtras, final String pushType) {
		final ResultObj resultObj = new ResultObj();

		try {
			final JGPushUtil jgPushUtil = new JGPushUtil(masterSecret, appKey);
			if (StringUtils.isEmpty(message)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("推送消息为空");

				return resultObj;
			}
			if (LongUtil.isEmpty(sendUserLogicId)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("发送者逻辑ID为空");

				return resultObj;
			}
			if (StringUtils.isEmpty(tags)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("别名为空");

				return resultObj;
			}
			if (StringUtils.isEmpty(pushType)) {
				resultObj.setResultFlag(false);
				resultObj.setResultMsg("推送环境类型为空");

				return resultObj;
			}
			// 别名集合
			final List<String> tagsList = new ArrayList<String>();
			final String[] aliasArray = tags.split(",");
			if (aliasArray != null && aliasArray.length > 0) {
				for (final String element : aliasArray) {
					tagsList.add(element);
				}
			}
			try {
				// 进行推送，返回推送结果
				final PushResult pushResult = jgPushUtil.buildPushObject_some_tags_alert(platforms, tagsList, message,
						pushType, pushExtras);
				Log.error("用户{}给{}发送一条推送消息", new Object[] { sendUserLogicId, tags });

				// 返回的结果为JSON型
				//			JSONObject jsonObject = JSONObject.fromObject(pushResult.toString());
				//			if (jsonObject.containsKey("msg_id") && jsonObject.containsKey("sendno")) {
				//				// 消息ID（极光）
				//				String msgId = (String)jsonObject.get("msg_id");
				//				// 发送编号（极光）
				//				String sendNo = (String)jsonObject.get("sendno");
				//			}

				resultObj.setResultFlag(true);
				resultObj.setObject(pushResult);
			} catch (final APIConnectionException e) {
				Log.error("用户{}给{}发送一条推送消息失败，原因为{}", new Object[] { sendUserLogicId, tags, e.getMessage() });
				resultObj.setResultFlag(false);
				resultObj.setResultMsg(e.getMessage());
			} catch (final APIRequestException e) {
				Log.error("用户{}给{}发送一条推送消息失败，原因为{}", new Object[] { sendUserLogicId, tags, e.getErrorMessage() });
				resultObj.setResultFlag(false);
				resultObj.setResultMsg(e.getErrorMessage());
			}
			return resultObj;
		} catch (final Exception e) {
			resultObj.setResultFlag(false);
			resultObj.setResultMsg(e.getMessage());
			return resultObj;
		}
	}

	/**
	 * 根据传入的json字符串来判断实现什么方式的推送通知内容为 ALERT
	 *
	 * @param jPushModelObj
	 *            极光推送所用实体
	 * @return 返回值
	 */
	@Override
	public ResultObj sendMobilePushAlertFromJson(final JPushModelObj jPushModelObj) {
		ResultObj resultObj = new ResultObj();

		try {
			if (StringUtils.isEmpty(jPushModelObj.getPushWay())) {
				resultObj = this.sendMobilePushAllPlatformAllDeviceAlert(jPushModelObj.getMasterSecret(),
						jPushModelObj.getAppKey(), jPushModelObj.getPlatform(), jPushModelObj.getMessage(),
						jPushModelObj.getSendLogicId(), jPushModelObj.getPushExtras(), jPushModelObj.getPushType());
			} else {
				if (StringUtils.equals(JPushModelObj.PUSHWAY_ALIAS, jPushModelObj.getPushWay())) {
					resultObj = this.sendMobilePushAllPlatformAliasAlert(jPushModelObj.getMasterSecret(),
							jPushModelObj.getAppKey(), jPushModelObj.getPlatform(), jPushModelObj.getMessage(),
							jPushModelObj.getSendLogicId(), jPushModelObj.getStringOfPushWay(),
							jPushModelObj.getPushExtras(), jPushModelObj.getPushType());
				} else if (StringUtils.equals(JPushModelObj.PUSHWAY_TAGS, jPushModelObj.getPushWay())) {
					resultObj = this.sendMobilePushAllPlatformTagsAlert(jPushModelObj.getMasterSecret(),
							jPushModelObj.getAppKey(), jPushModelObj.getPlatform(), jPushModelObj.getMessage(),
							jPushModelObj.getSendLogicId(), jPushModelObj.getStringOfPushWay(),
							jPushModelObj.getPushExtras(), jPushModelObj.getPushType());
				}
			}
			return resultObj;
		} catch (final Exception e) {
			resultObj.setResultFlag(false);
			resultObj.setResultMsg(e.getMessage());
			return resultObj;
		}
	}
}
